package dao

import (
	"express/config"
	"express/global"
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

//var db *gorm.DB

func InitDB() {
	//router := gin.Default()
	//
	//router.GET("/", func(context *gin.Context) {
	//	context.JSON(200, gin.H{
	//		"config": v.AllSettings(),
	//	})
	//	fmt.Println(v.GetString("Database.password"), v.Get("id")) // 获取单个配置属性
	//})
	//router.Run("127.0.0.1:8899")
	//
	//
	//
	v, _ := OnConfigChange()
	//v.WatchConfig()
	//
	//v.OnConfigChange(func(e fsnotify.Event) {
	//	fmt.Println("Config file changed:", e.Name)
	//	InitDB()
	//})

	//mysqlInfo := global.Settings.Mysqlinfo
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	host := v.GetString("Database.host")
	port := v.GetString("Database.port")
	database := v.GetString("Database.database")
	username := v.GetString("Database.username")
	password := v.GetString("Database.password")
	charset := v.GetString("Database.charset")
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=true",
		username,
		password,
		host,
		port,
		database,
		charset)
	global.DB, _ = gorm.Open(mysql.Open(dsn), &gorm.Config{
		PrepareStmt: true,
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true, // 使用单数表名
		},
	})

	//global.DB.AutoMigrate(&model.Users{})
}

func OnConfigChange() (v *viper.Viper, err error) {
	s, err := config.LoadConfigFromYaml()
	//修改配置文件回调
	s.WatchConfig()

	s.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("Config file changed:", e.Name)
		InitDB()
	})
	return s, err
}
